//
//  HMMainTabBar.swift
//  iOSWeibo11
//
//  Created by Apple on 16/7/18.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

class HMMainTabBar: UITabBar {
    
    // 闭包属性
    var composeCallback: (() -> Void)?
    
    // 懒加载按钮
    lazy var composeButton: UIButton = {
        let button = UIButton(type: UIButtonType.Custom)
        
        // 设置按钮图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置按钮背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 添加到tabbar里面
        self.addSubview(button)
        
        // 注册点击事件
        button.addTarget(self, action: "composeClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    // 按钮数量
    let itemCount: Int = 5

    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 计算每个按钮的宽度
        let newItemWidth = self.frame.width / CGFloat(itemCount)
        
        // 遍历所有的item
        var index = 0
        for item in self.subviews {
            // 判断如果是 UITabBarButton 类型,才需要设置frame
            // [UITabBarButton class]
            let cls = NSClassFromString("UITabBarButton")!
            if item.isKindOfClass(cls) {
//                print("item: \(item)")
                
                // 重新设置item的frame
                item.frame = CGRect(x: CGFloat(index) * newItemWidth, y: 0, width: newItemWidth, height: self.frame.height)
                
                index++
                // 当是第2个以后,在往后移动一个
                if index == 2 {
                    index++
                }
            }
        }
        
        // 设置
        composeButton.frame = CGRect(x: 2 * newItemWidth, y: 0, width: newItemWidth, height: self.frame.height)
    }

    // MARK: - 按钮点击事件
    func composeClick() {
//        print("composeClick")
        // View不能Modal出控制器
        composeCallback?()
    }
}
